package com.sc.admin.core.bo;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sc.common.entity.admin.menu.SysMenu;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class MenuBo {
    /**
     * 从根节点递归获取其所有子节点
     * @param groupMenusByPcodeMap
     * @param jsonArray
     */
    public void lookupAllChildrenMenu(final Map<String, List<SysMenu>> groupMenusByPcodeMap, final JSONArray jsonArray){
        if(jsonArray != null && jsonArray.size() > 0){
            for (Object o : jsonArray) {
                JSONObject jsonObject = (JSONObject)o;
                jsonObject.put("children",new JSONArray(10));
                String code = jsonObject.getString("code");


                List<SysMenu> children = groupMenusByPcodeMap.get(code);
                if(CollectionUtils.isNotEmpty(children)){
                    JSONArray childrenJSONArray = JSONArray.parseArray(JSONObject.toJSONString(children));
                    jsonObject.put("children",childrenJSONArray);
                    lookupAllChildrenMenu(groupMenusByPcodeMap,childrenJSONArray);
                }
            }
        }
    }



    /**
     * 对菜单按pcode分组
     * @param menus
     * @return 分组后的菜单集合
     */
    public Map<String,List<SysMenu>> groupMenusByPcode(List<SysMenu> menus){
        Map<String,List<SysMenu>> stringListMap = new HashMap<>();
        if(org.apache.commons.collections.CollectionUtils.isNotEmpty(menus)){
            for (SysMenu menu : menus) {
                String key = menu.getPcode();
                if(stringListMap.containsKey(key)){
                    stringListMap.get(key).add(menu);
                }else{
                    List<SysMenu> menuList = new ArrayList<>(10);
                    menuList.add(menu);
                    stringListMap.put(key,menuList);
                }
            }
            return stringListMap;
        }
        return null;
    }
}
